package com.bdqn.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.bdqn.pojo.Right;
import com.bdqn.service.RoleService;
import jakarta.annotation.Resource;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ShiroConfig {
    @Resource
    private RoleService roleService;

    /**
     * 自定义Realm
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm shiroRealm = new MyShiroRealm();
        return shiroRealm;
    }

    /**
     * 安全管理器SecurityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 注入Realm
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();
        shiroFilterFactory.setSecurityManager(securityManager);
        shiroFilterFactory.setLoginUrl("/login");
        shiroFilterFactory.setUnauthorizedUrl("/main");
        shiroFilterFactory.setUnauthorizedUrl("/403");

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 静态资源
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss", "anon");
        filterChainDefinitionMap.put("/localjs", "anon");

        // 登录和注销
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/logout", "logout");

        // 用户管理
        filterChainDefinitionMap.put("/user/list", "perms[user:list]");
        filterChainDefinitionMap.put("/user/add", "perms[user:add]");
        filterChainDefinitionMap.put("/user/edit", "perms[user:edit]");
        filterChainDefinitionMap.put("/user/del", "perms[user:del]");

        // 其他URL需要身份认证
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactory.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactory;
    }

    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() { //整合thymeleaf
        return new ShiroDialect();
    }

    /**
     * 开启shiro注解支持(如@RequiresRoles,@RequiresPermissions)，
     * 需借助SpringAop扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     * 配置以下俩个Bean即可实现此功能(DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor)
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 开启AOP注解支持
     */
//    @Bean
//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecretKeySpec securityManager) {
//        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
//        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
//        return authorizationAttributeSourceAdvisor;
//    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactory(java.lang.SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactory=new ShiroFilterFactoryBean();
        // 注入SecurityManager
        shiroFilterFactory.setSecurityManager(securityManager);

        // 权限验证：使用Filter控制资源(URL)的访问
        shiroFilterFactory.setLoginUrl("/index");
        shiroFilterFactory.setSuccessUrl("/main");
        shiroFilterFactory.setUnauthorizedUrl("/403");      // 没有权限跳转403页面

        Map<String,String> filterChainDefinitionMap=new LinkedHashMap<String, String>();    // 必须使用LinkedHashMap(有序集合)
        // 配置可以匿名访问的资源(URL):静态资源
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fonts/**","anon");
        filterChainDefinitionMap.put("/images/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/localcss/**","anon");
        filterChainDefinitionMap.put("/localjs/**","anon");

        filterChainDefinitionMap.put("/login","anon");
        filterChainDefinitionMap.put("/logout","logout");
        //配置需要特定权限才能访问的资源(URL)

        //静态授权：包括全部需要特定权限才能访问的资源(URL)
        filterChainDefinitionMap.put("/user/list","perms[用户列表]");
        filterChainDefinitionMap.put("/user/add","perms[用户添加]");
        filterChainDefinitionMap.put("/user/edit","perms[用户编辑]");
        filterChainDefinitionMap.put("/user/del","perms[用户删除");

        // 动态授权
        List<Right> rights=roleService.findAllRights();
        for (Right right:rights){
            if (right.getRightUrl()!=null && !right.getRightUrl().trim().equals("")){
                filterChainDefinitionMap.put(right.getRightUrl(),"perms["+right.getRightCode()+"]");
            }
        }

        //配置认证访问：其他资源(URL)必须认证通过才能访问；
        filterChainDefinitionMap.put("/**","authc"); //必须放在过滤器链的最后面

        shiroFilterFactory.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactory;
    }
}
